﻿package com.moonshineproject.plugin.actionscript.mxmlc 
{
	import com.moonshineproject.plugin.console.ConsoleOutputter;
	import com.moonshineproject.vo.Settings;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.utils.IDataInput;
	
	import mx.controls.Alert;
	
	public class CommandLine extends ConsoleOutputter
	{
		private function getShell():File
		{
			// TODO: Maybe this should be a setting.
			var shellPath:String;
			if (Settings.os == "win")
			{
				shellPath = "C:/Windows/System32/cmd.exe";
			}
			else
			{
				shellPath = "/bin/bash"
			}
			
			return new File(shellPath);
		}
		
		private var info:NativeProcessStartupInfo;
		private var inited:Boolean;
		
		public function CommandLine() 
		{
			var shell:File = getShell();
			if (!shell.exists) 
			{
				Alert.show("No shell found.");
				return;
			}
			
			info = new NativeProcessStartupInfo();
			info.executable = shell;
		}
		
		
		public function write(msg:String, workingDir:File = null):void 
		{
			if (workingDir) info.workingDirectory = workingDir;
			
			var proc:NativeProcess = new NativeProcess();
			proc.start(info);
			proc.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, readData);
			proc.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, readData);
			proc.addEventListener(NativeProcessExitEvent.EXIT, exit);
			proc.standardInput.writeMultiByte(msg+"\nexit\n", "us-ascii");
		}
		
		private function readData(e:ProgressEvent):void 
		{
			var output:IDataInput = (e.target as NativeProcess).standardOutput;
			debug("CMD: %s", output.readMultiByte(output.bytesAvailable, "us-ascii"));
		}
		
		private function exit(e:NativeProcessExitEvent):void 
		{
			debug("CMD exited with code %s", e.exitCode);
		}
	}
}